package com.cnxdc.demo.service.impl;

import com.cnxdc.demo.mapper.UserMapper;
import com.cnxdc.demo.service.UserService;
import com.cnxdc.demo.utils.Md5Util;
import com.cnxdc.demo.utils.ThreadLocalUtil;
import com.cnxdc.demo.vo.Result;
import com.cnxdc.demo.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public User findUserByUsername(String username) {
        return userMapper.findUserByUsername(username);
    }

    @Override
    public void register(User user) {
        //前台传过来的密码，加密操作
        String passwd=Md5Util.getMD5String(user.getPassword());
        user.setPassword(passwd);
        // 创建时间 和 修改时间!!!
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.register(user);
    }

    @Override
    public Result<User> doRegister(User user) {
        //判断用户名是否可用:是否存在
        User user1 = findUserByUsername(user.getUsername());
        if(user1!=null){
            return Result.error("用户名已存在");
        }
        // 注册
        register(user);// 不应该传递user1!!!
        return Result.success();
    }

    @Override
    public void update(User user) {
        // 更新了信息，更新时间要调整...
        // ... ...
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        user.setId(id);//前台传不传id，都能更新
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public void updatePic(String url) {
        //拿到id，拿到pic
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        User user=new User();
        user.setId(id);
        user.setUserPic(url);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateUserPic(user);
    }

    @Override
    public void updatePassword(Integer id,String newPwd) {
        User user=new User();
        user.setId(id);
        user.setPassword(Md5Util.getMD5String(newPwd));//密码是明文 ：加密
        user.setUpdateTime(LocalDateTime.now());//更新时间
        // 更新
        userMapper.updatePwd(user);
    }
}
